<?php
namespace control;

/*
*采购单类
*/

class purchaseOrderClass extends adIndexClass
{
    private const page = 'purchaseOrder';
    private const table = 'purchase_order';
    private const tableMx = 'purchase_order_detail';
    private const title = '采购订单';
    public const  scheduleState = ['','是','否'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'supplierPurchaseSearch':
                $tr = [
                    'orderNo'          => [
                        'name'  => '单据编号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'num' => [
                        'name'  => "数量",
                        'width' => 200,
                    ],
                    'money'  => [
                        'name'  => '采购金额(' . static::$unit . ')',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'deliveryDate'         => [
                        'name'  => '交货日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'recordDate'          => [
                        'name'  => '单据日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 200,
                    ]
                ];
                break;
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '单据编号',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'supplier' => [
                        'name'  => "供应商",
                        'width' => 200,
                    ],
                    'tag'  => [
                        'name'  => "单据标签",
                        'width' => 200,
                    ],
                    'num'         => [
                        'name'  => '数量',
                        'width' => 150,
                    ],
                    'money'          => [
                        'name'  => '采购金额(' . static::$unit . ')',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'deliveryDate'          => [
                        'name'  => '交货日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'deliver_on_schedule'          => [
                        'name'  => '按期交货',
                        'width' => 150,
                    ],
                    'recordDate'          => [
                        'name'  => '单据日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 150,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function supplierPurchaseOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")).hidden(array("name" => "targetId", "value" => $this->get('id'))),
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态" => select(["name" => "state", 'option' => ['草稿', '待确认', '已确认']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 供应商页卡
     * @return bool|string
     */
    public function supplierPurchase(): bool|string
    {
        $html = $this->supplierPurchaseOptions(false);
        $button = "";
        if ($this->power(self::page, "print")) {
            $button .= sprintf("<span onclick=\"batchPrint('%s', {targetId: '%s'})\" class='spanButton'>打印设置</span>\n", $this->get('cla'), $this->get('id'));
        }
        //返回
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
    }

    public function supplierPurchaseSearch(): bool|string
    {
        $targetId = $this->post('targetId');
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),
            'coid' => self::$coid
        );
        $and = " and supplierId = '$targetId'";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate desc,time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //生成查询语句
        $where = search([
                "=" => $equal,
                "like" => $like,
            ]) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array("");
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "detail" => ["title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=detail&id=' . $array['id'] . "')"],
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "num":
                        $num = find(array('table' => self::tableMx, 'where' => "orderId = '$array[id]'", 'sum' => "num"));
                        $row[] = $num;
                        break;
                    case "money":
                        $row[] = self::lostZero($array['money']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='invoiceForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "标签"   => text(array("name" => "tages")),
                    '供应商' => supplierClass::supplierSelect(array()),
                ],
                [
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    '按期交货' => select(["name" => "deliver_on_schedule", 'option' => [1=>'是', 2=>'否']]),
                ],
                [
                    "状态" => select(["name" => "state", 'option' => ['草稿', '待确认', '已确认']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        $isEdit = $this->power(self::page, "edit");
        if ($isEdit) {
            $button .= "
            <span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($isEdit) {
            $button .= "
             <span onclick=\"layer('orderTag','batchAddTags',{'table':'".self::table."','title':'".self::title."'})\" class='spanButton'>批量打标签</span>\n";
        }
        if ($this->power(self::page, "print")) {
            $button .= " <span onclick=\"batchPrint('" . $this->get('cla') . "')\" class='spanButton'>批量打印</span>\n";
        }
        if ($this->power(self::page, "close")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'close'})\">批量关闭业务</span>\n";
        }
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if (para('CSAIII') == '是') {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'batchSure'})\">批量提交确认</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            "deliver_on_schedule" => $this->post('deliver_on_schedule'),
            "state" => $this->post('state'),
            "supplierId" => $this->post('supplierId'),
            'coid' => self::$coid
        );
        $and = '';
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
        }
        if ($this->post('tages')) {
            $and .= " and (";
            $tagsArr = explode('，', $this->post('tages'));
            foreach ($tagsArr as $index => $tag) {
                $and .= $index == 0 ? "tags like '%" . $tag . "%'" : " and tags like '%" . $tag . "%'";
            }
            $and .= ")";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate desc,orderNo',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        $isEdit = $this->power(self::page, "edit");
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
                'print' => array('title' => '打印', 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"),
                'track' => array("title" => "单据追踪", "click" => "newIframe('单据追踪','" . root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=采购订单&id=" . $array['id'] . "')"),
            );
            if ($array['state'] != '草稿' || !$isEdit) {
                unset($dominate['edit']);
            }
            if ($array['isClose'] == 1) {
                $array['state'] = '已完成';
            }
            $closeSign = $array['isClose'] ? "<span class='no-choose'></span>" : '';//关闭单据颜色显示标志
            $liButton[] = $this->dominate($dominate) . $closeSign;
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "supplier":
                        $supplier = query('supplier', "id = '$array[supplierId]'");
                        $row[] = $supplier['name'];
                        break;
                    case "tag":
                        $tag = orderTagClass::getTagName($array['id']);
                        $row[] = $tag;
                        break;
                    case "num":
                        $num = find(array('table' => self::tableMx, 'where' => "orderId = '$array[id]'", 'sum' => "num"));
                        $row[] = $num;
                        break;
                    case "deliver_on_schedule":
                        $row[] = self::scheduleState[$array['deliver_on_schedule']];
                        break;
                    case "money":
                        $row[] = self::lostZero($array['money']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalNum = find([
            'table'  => self::tableMx,
            'single' => "orderId in (select id from ".self::table." where 1=1 {$where})",
            'field'  => "ifnull(sum(num),0) as num",
        ]);
        $totalMoney = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(money),0) as money",
        ]);
        $total    = [
            'num'        => self::lostZero($totalNum['num'], 'numPrecision'),
            'money'      => self::lostZero($totalMoney['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . machiningOrderClass::closeJs() . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'import')) {
            $_SESSION['warn'] = '你还没有导入的权限';
        }  else {
            $exampleData[] = [
                '2023-02-24', 'S0001', 'A供应商', 'C0001', 'A供应商的采购合同', '月结', 30, '2023-03-24', '李四', '13000000000', '重庆市', '样例数据', '否', 'CP0001', 'A产品', '包', 100, 50, 5, '', '测试数据'
            ];
            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $filePath->insertText($y+1, $index, $example[$k]??'');
                    }
                    $index++;
                }
            }

            $text = $this->control['name'] . "下载了" . self::title . "导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*数据导入*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'import')) {
            $json['warn'] = '你还没有导入的权限';
        } else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            $purchaseOrder = [];
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    //  ['*单据日期', '*供应商编码', '供应商名称', '采购合同编号', '采购合同名称', '*结算方式', '结算周期', '交货日期', '收货人','收货电话','收货地址','单据备注','*是否含税(是/否，默认否)','*物料编码','物料名称','*单位','*数量','*单价','*税率%','价税合计(不填则根据单价、数量、税率自动计算，填则根据数量和税率反算单价)','备注'];
                    if (!empty($cell['单据日期'])) {
                        $purchaseOrder = [];
                        if ($cell[1]){
                            $supplier = query('supplier', "coid = '" . self::$coid . "' and code = '$cell[供应商编码]'");
                        }else{
                            $supplier = query('supplier', "coid = '" . self::$coid . "' and name = '$cell[供应商名称]'");
                        }

                        $purchase_contract = query('purchase_contract', "coid = '" . self::$coid . "' and orderNo = '$cell[3]'");
                        $field = [
                            'type' => '购货',
                            'text' => $cell['单据备注'],
                            'contractId' => $purchase_contract['id'],
                            'supplierId' => $supplier['id'],
                            'recordDate' => self::importDateFormat($cell['单据日期']),
                            'deliveryDate' => self::importDateFormat($cell['交货日期']),
                            'contactName' => $cell['收货人'],
                            'contactTel' => $cell['收货电话'],
                            'address' => $cell['收货地址'],
                            'isTax' => $cell['是否含税'] == '是' ? 1 : 0,
                            'settlementType' => $cell['结算方式'],
                            'settlementDay' => $cell['结算周期'],
                        ];
                        $annotation = [
                            'supplierId' => '供应商',
                            'recordDate' => '单据日期',
                        ];
                        $rules = [
                            'supplierId' => 'required',
                            'recordDate' => 'required|date',
                        ];
                        // 校验是否符合规则
                        $vt = new \verify();
                        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                        if ($result === false) {
                            $text .= "\n第【{$row_list}】行，" . $vt->getErrs()[0];
                        } else {
                            // 新增
                            $userNo = codeTemplateClass::generateCode(self::page, [
                                'prefix' => 'CGDD' . date('Ymd', strtotime($field['recordDate'])),
                                'table' => self::table,
                                'field' => 'orderNo',
                                'where' => " and coid = '" . self::$coid . "'",
                            ], $field);
                            $field = array_merge($field, [
                                'id' => suiji(),
                                'orderNo' => $userNo,
                                'state' => '草稿',
                                'coid' => self::$coid,
                                'stid' => $this->control['stid'],
                            ]);
                            $warn = static::insert([
                                "table" => self::table,
                                "field" => $field,
                            ]);
                            if (in_array($warn, ["新增成功", "更新成功"])) {
                                $purchaseOrder = $field;
                            } else {
                                $text .= "\n第【{$row_list}】行，插入主数据失败，".$warn;
                            }
                        }
                    }

                    if (isset($purchaseOrder['id']) && !empty($purchaseOrder['id'])) {
                        if ($cell['物料编码']){
                            $material = query('material', "coid = '" . self::$coid . "' and code = '$cell[物料编码]'");
                        }else{
                            $material = query('material', "coid = '" . self::$coid . "' and name = '$cell[物料名称]'");
                        }
                        if(empty($material['id'])){
                            $text .= "\n第【{$row_list}】行，未通过编码找到此物料";
                        }elseif (!in_array($cell['单位'],machiningOrderClass::unitOption($material['id']))){
                            $text .= "\n第【{$row_list}】行，单位【{$cell['单位']}】不在此物料的可选单位范围内";
                        }else{
                            $cell['税率'] = floatval($cell['税率']) / 100;;
                            //明细
                            $cell['数量'] = self::formattingFigure($cell['数量'], 'numPrecision');
                            $cell['单价'] = self::formattingFigure($cell['单价'], 'pricePrecision');
                            if (!empty($cell['价税合计'])) {
                                $result = saleOrderClass::priceAndMoney($cell['价税合计'], $cell['税率'], $purchaseOrder['isTax'], $cell['数量'] ?: 0);
                                $cell['单价'] = self::formattingFigure($result['price'], 'pricePrecision');
                            }
                            $result = saleOrderClass::isTax($cell['数量'] ?: 0, $cell['单价'] ?: 0, $cell['税率'], $purchaseOrder['isTax']);
                            $mxField = [
                                'id' => suiji(),
                                'orderId' => $purchaseOrder['id'],
                                'coid' => self::$coid,
                                'materialId' => $material['id'],
                                'unit' => $cell['单位'],
                                'num' => $cell['数量'],
                                'price' => $cell['单价'],
                                'taxMoney' => $result['taxMoney'],//税额
                                'moneyWithOutTax' => $result['money'],//不含税金额
                                'money' => $cell['价税合计'] ?: $result['moneyWithTax'],//价税合计
                                'rate' => $cell['税率'],
                                'text' => $cell['备注'],
                            ];
                            $warn = static::insert([
                                "table" => self::tableMx,
                                "field" => $mxField,
                            ]);
                            if (in_array($warn, ["新增成功", "更新成功"])) {
                                $text .= "\n第【{$row_list}】行，导入成功";
                                $money = find(array(
                                    'table' => self::tableMx,
                                    'single' => "orderId = '$purchaseOrder[id]'",
                                    'field' => "ifnull(sum(money),0) as total"
                                ))['total'];
                                update(array('table' => self::table, 'field' => ['money' => self::formattingFigure($money)], 'where' => "id = '$purchaseOrder[id]'"));
                            } else {
                                $text .= "\n第【{$row_list}】行，导入失败：插入数据库失败";
                            }
                        }


                    } else {
                        $text .= "\n第【{$row_list}】行，未找到单据";
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }

    /**
     * 合并物料
     */
    public static function mergeMaterial($listId): array
    {
        $result = [];
        if (empty($listId)) {
            return $result;
        } else {
            $listArr = explode(',', $listId);
            foreach ($listArr as $id) {
                $machining_demands = query('machining_demands', "id = '$id'");
                $material = query('material', "id = '$machining_demands[materialId]'");
                $supplyControl = explode(',', $material['supplyControl']);
                if (in_array('允许采购', (array)$supplyControl)) {
                    if (!array_key_exists($machining_demands['materialId'], $result)) {
                        $result[$machining_demands['materialId']] = [
                            'num' => machiningOrderClass::material_num_change($machining_demands['materialId'], $machining_demands['unit'], $material['unit'], $machining_demands['num']),
                            'unit' => $material['unit'],
                            'materialId' => $machining_demands['materialId'],
                        ];
                    } else {
                        $result[$machining_demands['materialId']]['num'] = $result[$machining_demands['materialId']]['num'] + machiningOrderClass::material_num_change($machining_demands['materialId'], $machining_demands['unit'], $result[$machining_demands['materialId']]['unit'], $machining_demands['num']);
                    }
                }
            }
        }
        return $result;
    }
    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }
    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id') ?: self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        $checked = $info['isTax'] ? 'checked' : '';
        $button[] = [
            "name" => "保存为草稿",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')"
        ];
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => "保存并提交",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')"
        ];
        $tr[] = ['', '物料编码', '物料名称', '规格型号', '单位', '数量', '单价(' . static::$unit . ')', '未税金额（' . static::$unit . '）', '<div class="rate">' . '税率%' . saleOrderClass::chooseRate() . '</div>', '税额（' . static::$unit . '）', '价税合计（' . static::$unit . '）', '关联源单', '源单类型', '备注'];
        $totalArr = ['total_num'=>0,'total_row_money'=>0,'total_tax_money'=>0,'total_money'=>0];
        if ($this->get('source') == 'materialDemand') {
            //材料需求，合并过，不能追溯
            $id = self::getId();
            $listId = $this->get('listId');
            $result = self::mergeMaterial($listId);//合并相同的物料
            $k = 0;
            foreach ($result as $array) {
                $material = query('material', " id = '$array[materialId]'");
                $num = self::formattingFigure(machiningOrderClass::material_num_change($material['id'], $array['unit'], $material['unit'], $array['num']), 'numPrecision');
                $moneyRes = saleOrderClass::isTax($num, $material['buyPrice'], $material['buyRate'], $info['isTax']);
                $tr[] = [
                    componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => self::getId())) .
                    hidden(array('name' => 'materialId[]', 'value' => $array['materialId'])) .
                    hidden(array('name' => 'sourceId[]', 'value' => '')),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    select(array('name' => 'unitDetail[]', 'data' => ['unit' => $material['unit']], 'change' => 'unitChange', 'option' => machiningOrderClass::unitOption($material['id']), 'title' => '单位', 'value' => $material['unit'])),
                    text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision'), 'blur' => 'countMoney', 'value' => $num)),
                    text(array('name' => 'price[]', 'other' => self::digitalFiltering('pricePrecision'), 'blur' => 'countMoney', 'value' => self::lostZero($material['buyPrice'], 'pricePrecision'))),
                    "<span class='rowMoney'>" . self::lostZero($moneyRes['money']) . "</span>",
                    select(array('name' => 'rate[]', 'change' => 'countMoney', 'title' => '税率', 'option' => explode('，', para('taxRate')), 'value' => $material['buyRate'] * 100)),
                    "<span class='taxMoney'>" . self::lostZero($moneyRes['taxMoney']) . "</span>",
                    text(array('name' => 'moneyWithTax[]', 'other' => self::digitalFiltering(), 'blur' => 'calculatePrice', 'value' => self::lostZero($moneyRes['moneyWithTax']))),
                    '',
                    '',
                    text(array('name' => 'mxText[]', 'class' => 'text textPrice', 'value' => '')),
                ];
                $totalArr['total_num'] += $num;
                $totalArr['total_row_money'] += $moneyRes['money'];
                $totalArr['total_tax_money'] += $moneyRes['taxMoney'];
                $totalArr['total_money'] += $moneyRes['moneyWithTax'];
            }
        } elseif ($this->get('source') === 'demand') {
            //外购产品需求
            $listId = explode(',', $this->get('listId'));
            foreach ($listId as $k=>$demandsId) {
                $relativeNo = '';
                $relativeType = '';
                $purchase_demands = query('purchase_demands', "id = '$demandsId'");
                if (!isset($info['supplierId']) || empty($info['supplierId'])) {
                    $info['supplierId'] = $purchase_demands['supplierId'];
                }
                if ($purchase_demands['sourceType'] == '销售订单') {
                    $saleOrder = query('sale_order', "id = '$purchase_demands[sourceId]'");
                    $relativeNo = $saleOrder['orderNo'];
                    $relativeType = '销售订单';
                } elseif ($purchase_demands['sourceType'] == '生产计划') {
                    $machiningOrder = query('machining_order', "id = '$purchase_demands[sourceId]'");
                    $relativeNo = $machiningOrder['orderNo'];
                    $relativeType = '生产计划单';
                }
                $material = query('material', " id = '$purchase_demands[materialId]'");
                $num = self::formattingFigure(machiningOrderClass::material_num_change($purchase_demands['materialId'], $purchase_demands['unit'], $material['unit'], $purchase_demands['num']), 'numPrecision');
                $moneyRes = saleOrderClass::isTax($num, $material['buyPrice'], $material['buyRate'], $info['isTax']);
                $money = self::lostZero($moneyRes['money']);
                $taxMoney = self::lostZero($moneyRes['taxMoney']);
                $tr[] = [
                    componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => self::getId())) .
                    hidden(array('name' => 'materialId[]', 'value' => $purchase_demands['materialId'])) .
                    hidden(array('name' => 'sourceId[]', 'value' => $purchase_demands['id'])),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    select(array('name' => 'unitDetail[]', 'data' => ['unit' => $material['unit']], 'change' => 'unitChange', 'option' => machiningOrderClass::unitOption($material['id']), 'title' => '单位', 'value' => $material['unit'])),
                    text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision'), 'blur' => 'countMoney', 'value' => $num)),
                    text(array('name' => 'price[]', 'other' => self::digitalFiltering('pricePrecision'),'blur' => 'countMoney', 'value' => self::lostZero($material['buyPrice'], 'pricePrecision'))),
                    "<span class='rowMoney'>" . $money . "</span>",
                    select(array('name' => 'rate[]', 'change' => 'countMoney', 'title' => '税率', 'option' => explode('，', para('taxRate')), 'value' => $material['buyRate'] * 100)),
                    "<span class='taxMoney'>{$taxMoney}</span>",
                    text(array('name' => 'moneyWithTax[]', 'other' => self::digitalFiltering(), 'blur' => 'calculatePrice', 'value' => self::lostZero($moneyRes['moneyWithTax']))),
                    $relativeNo,
                    $relativeType,
                    text(array('name' => 'mxText[]', 'class' => 'text textPrice', 'value' => '')),
                ];
                $totalArr['total_num'] += $num;
                $totalArr['total_row_money'] += $money;
                $totalArr['total_tax_money'] += $taxMoney;
                $totalArr['total_money'] += $moneyRes['moneyWithTax'];
            }
        } else {
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($result['array'] as $k=>$array) {
                $relativeNo = '';
                $relativeType = '';
                $material = query('material', " id = '$array[materialId]'");
                $money = self::formattingFigure($array['money'] - $array['taxMoney']);
                if ($array['sourceTable'] == 'purchase_apply_detail') {
                    $targetInfo = query('purchase_apply_detail', "id = '$array[sourceId]'");
                    $purchaseApply = query('purchase_apply', "id = '$targetInfo[orderId]'");
                    $relativeNo = $purchaseApply['orderNo'];
                    $relativeType = '采购申请单';
                } elseif ($array['sourceTable'] == 'purchase_demands') {
                    $targetInfo = query('purchase_demands', "id = '$array[sourceId]'");
                    if ($targetInfo['sourceType'] == '销售订单') {
                        $saleOrder = query('sale_order', "id = '$targetInfo[sourceId]'");
                        $relativeNo = $saleOrder['orderNo'];
                        $relativeType = '销售订单';
                    } elseif ($targetInfo['sourceType'] == '生产计划') {
                        $machining_order = query('machining_order', "id = '$targetInfo[sourceId]'");
                        $relativeNo = $machining_order['orderNo'];
                        $relativeType = '生产计划单';
                    }
                } elseif ($array['sourceTable'] == 'purchase_contract_detail') {
                    $targetInfo = query('purchase_contract_detail', "id = '$array[sourceId]'");
                    $purchaseContract = query('purchase_contract', "id = '$targetInfo[orderId]'");
                    $relativeNo = $purchaseContract['orderNo'];
                    $relativeType = '采购合同';
                }
                $tr[] = [
                    componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                    hidden(array('name' => 'materialId[]', 'value' => $array['materialId'])) .
                    hidden(array('name' => 'sourceId[]', 'value' => $array['sourceId'])),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    select(array('name' => 'unitDetail[]', 'data' => ['unit' => $array['unit']], 'change' => 'unitChange', 'option' => machiningOrderClass::unitOption($material['id']), 'title' => '单位', 'value' => $array['unit'])),
                    text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision'), 'blur' => 'countMoney', 'value' => self::lostZero($array['num'], 'numPrecision'))),
                    text(array('name' => 'price[]', 'other' => self::digitalFiltering('pricePrecision'), 'blur' => 'countMoney', 'value' => self::lostZero($array['price'], 'pricePrecision'))),
                    "<span class='rowMoney'>{$money}</span>",
                    select(array('name' => 'rate[]', 'change' => 'countMoney', 'title' => '税率', 'option' => explode('，', para('taxRate')), 'value' => $array['rate'] * 100)),
                    "<span class='taxMoney'>{$array['taxMoney']}</span>",
                    text(array('name' => 'moneyWithTax[]', 'other' => self::digitalFiltering(), 'blur' => 'calculatePrice', 'value' => self::lostZero($array['money']))),
                    $relativeNo,
                    $relativeType,
                    text(array('name' => 'mxText[]', 'class' => 'text textPrice', 'value' => $array['text'])),
                ];
                $totalArr['total_num'] += $array['num'];
                $totalArr['total_row_money'] += $money;
                $totalArr['total_tax_money'] += $array['taxMoney'];
                $totalArr['total_money'] += $array['money'];
            }
        }
        $total = [
            5 => "<span id='total_num'>".self::lostZero($totalArr['total_num'],'numPrecision')."</span>",
            7 => "<span id='total_row_money'>".self::lostZero($totalArr['total_row_money'])."</span>",
            9 => "<span id='total_tax_money'>".self::lostZero($totalArr['total_tax_money'])."</span>",
            10 => "<span id='total_money'>".self::lostZero($totalArr['total_money'])."</span>",
        ];
        $list = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total));

        $chooseBtn = <<<eof
<span class="smallButton" onclick="layer('{$this->get('cla')}','addMx',$('form[name=purchaseOrderEditForm]').serialize())">选择物料</span>
eof;
        //选项控制
        $setting = optionSettingClass::getSetting('采购');
        if (isset($setting['purchaseApplyStrict']) && $setting['purchaseApplyStrict']) {
            $chooseBtn = '';
        }
        $mxButton = <<<efo
                <span class="smallButton" onclick="layer('{$this->get('cla')}','addContractMx',$('form[name=purchaseOrderEditForm]').serialize())">选择合同物料明细</span>
               <span class="smallButton" onclick="layer('{$this->get('cla')}','addOrder',$('form[name=purchaseOrderEditForm]').serialize())">关联采购申请</span>
                $chooseBtn
                <span class="smallButton" onclick="layer('{$this->get('cla')}','addSupplierPrice',$('form[name=purchaseOrderEditForm]').serialize())">选择供应商物料</span>
                <span style="margin-left: 20px;">
                    <label class='checkbox'><input name='isTax' onclick="taxChange(this)" type='checkbox' $checked value='1'><span></span>&nbsp;含税</label>
                </span>
efo;

        $contact = query(self::table, "coid = '" . self::$coid . "' and contactName !='' order by time desc");

        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . "供应商：" => supplierClass::supplierSelect(array('value'=>$info['supplierId'],'change' => "getContract",'param'=>"{type:'启用'}")),
                    //selectMultiple(["name" => "supplierId", 'change' => 'getContract', "value" => $info['supplierId'], 'where' => "coid = '" . self::$coid . "' and state = '启用'", 'table' => "supplier", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => '请选择']),
                    "合同：" =>
                        "<div id='contract' class='full'>" .
                        selectMultiple(["name" => "contractId", "value" => $info['contractId'], 'table' => "purchase_contract", 'where' => "supplierId = '$info[supplierId]' and state = '已通过' and coid = '" . self::$coid . "'", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => '请选择']) .
                        "</div>",
                    "结算方式：" => radio(array('name' => 'settlementType', 'change' => 'settlementDayDefault', 'checked' => $info['settlementType'], 'value' => array_merge(para('supplierSettlement', '，'), ['月结']))) . "&nbsp;" .
                        text(array('name' => 'settlementDay', 'type' => 'number', 'value' => $info['settlementDay'], 'title' => '结算周期'))
                ],
                [
                    must . "单据日期：" => text(["name" => "recordDate", 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                    must . "交货日期：" => text(["name" => "deliveryDate", 'laydate' => [], "value" => $info['deliveryDate']]),
                    "收货人：" => text(["name" => "contactName", 'class' => 'text', "value" => $info['id'] ? $info['contactName'] : $contact['contactName']]),
                    "收货电话：" => text(["name" => "contactTel", 'class' => 'text', "value" => $info['id'] ? $info['contactTel'] : $contact['contactTel']]),
                ],
                [
                    "收货地址：" => textarea(["name" => "address", 'class' => 'text', "value" => $info['id'] ? $info['address'] : $contact['address']]),
                ],
                [
                    "备注：" => textarea(["name" => "text", "value" => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '订单明细',
            'button' => $mxButton,
            'html' => $list,
        ]);
        $body .= $this->editBlock([
            '附件' => fileUploadClass::addFileComponent($id, '采购单', self::page, self::page . 'EditForm')
        ]);

        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $saleOrderObj = new saleOrderClass();
        $data['html'] .= <<<efo
<script>

function getContract(data){
    let supplierId = data.id;
    let val = $("[name='contractId']").val();
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getContract',{supplierId:supplierId,value:val},function(res) {
          $("#contract").html(res.html);
          $("[name='settlementType'][value='"+res.settlementType+"']").attr('checked',true)
    },'json');
}
function addRow(classify = ''){
   if (classify =='addContractMx'){
        $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addContractMxEdit',$("form[name='purchaseContractForm']").serialize(),function(res) {
            $('#purchaseOrderAddContractMx').hide();
            $("#materialTable tbody").append(res.html);
        },'json');
    }else if (classify === 'purchaseApply'){
        $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addOrderEdit',$("form[name='saleOrderForm']").serialize(),function(res) {
            $("#materialTable tbody").append(res.html);
            resetNumber($("#materialTable"))
        },'json');
    }else if(classify === 'supplierPrice'){
        $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addSupplierPriceEdit',$("form[name='supplierPriceForm']").serialize(),function(res) {
            $("#materialTable tbody").append(res.html);
            resetNumber($("#materialTable"))
        },'json');
    }else{
        $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
            $("#materialTable tbody").append(res.html);
            resetNumber($("#materialTable"))
        },'json');
    }
}

</script>
efo. $saleOrderObj->editJs();
        //返回
        return $this->tab($data);
    }

    /**
     * 获取合同
     */
    public function getContract()
    {
        $supplierId = $this->post('supplierId');
        $value = $this->post('value');
        $supplier = query('supplier', "id = '$supplierId'");
        $json['settlementType'] = $supplier['settlement'];
        $json['html'] = selectMultiple(["name" => "contractId", "value" => $value, 'table' => "purchase_contract", 'where' => "supplierId = '$supplierId' and state = '已通过' and coid = '" . self::$coid . "' order by time desc", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => '请选择']);
        return json_encode($json, 320);
    }

    /**
     * 已在采购单中的数量
     * @param $purchaseOrderId
     * @param $sourceId
     * @param $toUnit
     * @return float
     */
    private function purchaseNum($purchaseOrderId, $sourceId, $toUnit): float
    {
        $refundNum = 0;
        $all = find(array('table' => 'purchase_order_detail', "where" => "sourceId = '$sourceId' and id !='$purchaseOrderId' and coid = '" . self::$coid . "'"));
        foreach ($all['array'] as $array) {
            $refundNum += machiningOrderClass::material_num_change($array['materialId'], $array['unit'], $toUnit, $array['num']);
        }
        return self::formattingFigure($refundNum, 'numPrecision');
    }

    public function editEdit()
    { //附件
        $fileIdArr = $this->post('fileId');
        $id = $this->post('id') ?: self::getId();
        $mxIdArr = $this->post('mxId') ?: [];
        $materialIdArr = $this->post('materialId');
        $sourceIdArr = $this->post('sourceId');
        $numArr = $this->post('num');
        $unitArr = $this->post('unitDetail');
        $priceArr = $this->post('price');
        $mxTextArr = $this->post('mxText');
        $taxRateArr = $this->post('rate');
        $moneyWithTaxArr = $this->post('moneyWithTax');
        $field = [
            'type' => '购货',
            'text' => $this->post('text'),
            'supplierId' => $this->post('supplierId'),
            'contractId' => $this->post('contractId'),
            'recordDate' => $this->post('recordDate'),
            'deliveryDate' => $this->post('deliveryDate'),
            'contactName' => $this->post('contactName'),
            'contactTel' => $this->post('contactTel'),
            'address' => $this->post('address'),
            'settlementType' => $this->post('settlementType'),
            'settlementDay' => $this->post('settlementDay'),
            'isTax' => $this->post('isTax') ? 1 : 0
        ];
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (!empty($info['id']) && $info['state'] == '已确认') {
            $json['warn'] = '此采购单已确认，不能修改';
        } else {
            $json['warn'] = '';
            if ($field['type'] == '采购') {
                //判断数量是否超过总数量
                foreach ($mxIdArr as $k => $mxId) {
                    if (isset($sourceIdArr[$k]) && $sourceIdArr[$k]) {
                        //采购申请明细
                        $targetInfo = query('purchase_apply_detail', "id = '$sourceIdArr[$k]'");
                        $num = $this->purchaseNum($id, $targetInfo['id'], $targetInfo['unit']);
                        $type = '采购申请单';
                        if (empty($targetInfo['id'])) {
                            //采购合同明细
                            $targetInfo = query('purchase_contract_detail', "id = '$sourceIdArr[$k]'");
                            $material = query('material', "id = '$targetInfo[materialId]'");
                            $targetInfo['unit'] = $material['unit'];
                            $type = '采购合同明细';
                            $num = $this->purchaseNum($id, $targetInfo['id'], $material['unit']);
                        }

                        if (isset($targetInfo['materialId']) && $targetInfo['materialId']) {
                            $material = query('material', "id = '$targetInfo[materialId]'");
                            $purchaseNum = machiningOrderClass::material_num_change($targetInfo['materialId'], $unitArr[$k], $targetInfo['unit'], $numArr[$k]);
                            if (self::formattingFigure($num + $purchaseNum, 'numPrecision') > $targetInfo['num']) {
                                $json['warn'] = "物料【{$material['name']}】的数量已超出{$type}中数量";
                                break;
                            }
                        }
                    }
                }
            }

            if (empty($json['warn'])) {
                $this->startTrans();
                $isPass = true;//事务通过标志
                if (!$info['id']) {
                    $userNo = codeTemplateClass::generateCode(self::page, [
                        'prefix' => 'CGDD' . date('Ymd', strtotime($field['recordDate'])),
                        'table' => self::table,
                        'field' => 'orderNo',
                        'where' => " and coid = '" . self::$coid . "'",
                    ], $field);
                    $field = array_merge($field, [
                        'id' => $id,
                        'orderNo' => $userNo,
                        'state' => '草稿',
                        'coid' => self::$coid,
                        'stid' => $this->control['stid'],
                    ]);
                    $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
                } else {
                    $json['warn'] = static::update([
                        "table" => self::table,
                        "field" => $field,
                        "where" => $where
                    ]);
                }

                //添加或更新明细
                if (is_array($mxIdArr)) {
                    foreach ($mxIdArr as $k => $nid) {
                        $mx = query(self::tableMx, "id = '$nid'");
                        //数据格式处理
                        $taxRateArr[$k] = floatval($taxRateArr[$k]) / 100;//税率从百分比转为小数
                        $numArr[$k] = self::formattingFigure($numArr[$k], 'numPrecision');
                        $priceArr[$k] = self::formattingFigure($priceArr[$k], 'pricePrecision');
                        $result = saleOrderClass::isTax($numArr[$k], $priceArr[$k], $taxRateArr[$k], $field['isTax']);

                        //采购申请明细
                        $targetInfo = query('purchase_apply_detail', "id = '$sourceIdArr[$k]'");
                        $sourceTable = 'purchase_apply_detail';
                        if (empty($targetInfo['id'])) {
                            //采购合同明细
                            $targetInfo = query('purchase_contract_detail', "id = '$sourceIdArr[$k]'");
                            $sourceTable = 'purchase_contract_detail';
                        }
                        if (empty($targetInfo['id'])) {
                            //外购产品需求
                            $targetInfo = query('purchase_demands', "id = '$sourceIdArr[$k]'");
                            $sourceTable = 'purchase_demands';
                        }
                        if (empty($targetInfo['id'])) {
                            $sourceTable = '';
                        }
                        if (!empty($mx['id'])) {
                            //更新
                            $warn = static::update([
                                "table" => self::tableMx,
                                "field" => [
                                    'sourceId' => $sourceIdArr[$k],
                                    'sourceTable' => $sourceTable,
                                    'materialId' => $materialIdArr[$k],
                                    'unit' => $unitArr[$k],
                                    'num' => $numArr[$k],
                                    'price' => $priceArr[$k],
                                    'taxMoney' => $result['taxMoney'],//税额
                                    'moneyWithOutTax' => $result['money'],//不含税金额
                                    'money' => self::formattingFigure($moneyWithTaxArr[$k]),//价税合计
                                    'rate' => $taxRateArr[$k],
                                    'text' => $mxTextArr[$k],
                                ],
                                "where" => " id = '$nid'"
                            ]);
                        } else {
                            //新增
                            $warn = static::insert([
                                "table" => self::tableMx,
                                "field" => [
                                    'id' => $nid,
                                    'orderId' => $id,
                                    'coid' => self::$coid,
                                    'sourceId' => $sourceIdArr[$k],
                                    'sourceTable' => $sourceTable,
                                    'materialId' => $materialIdArr[$k],
                                    'unit' => $unitArr[$k],
                                    'num' => $numArr[$k],
                                    'price' => $priceArr[$k],
                                    'taxMoney' => $result['taxMoney'],//税额
                                    'moneyWithOutTax' => $result['money'],//不含税金额
                                    'money' => self::formattingFigure($moneyWithTaxArr[$k]),//价税合计
                                    'rate' => $taxRateArr[$k],
                                    'text' => $mxTextArr[$k],
                                ],

                            ]);
                        }
                        if (!in_array($warn, ['新增成功', '更新成功'])) {
                            $isPass = false;
                            $json['warn'] = $warn;
                            break;
                        }
                    }
                }
                //添加主表ID到附件表
                if (is_array($fileIdArr)) {
                    $warn = update(array(
                        'table' => 'file',
                        'field' => ['targetId' => $id],
                        'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"
                    ));
                    if ($warn != '更新成功') {
                        $json['warn'] = $warn;
                        $isPass = false;
                    }
                }
                if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
                    $this->commitTrans();
                    delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
                    $money = find(array('table' => self::tableMx, 'single' => "orderId = '$id'", 'field' => "ifnull(sum(money),0) as total"))['total'];
                    update(array('table' => self::table, 'field' => ['money' => self::formattingFigure($money)], 'where' => "id = '$id'"));
                    if ($json['warn'] == '新增成功') {
                        self::insertOperateLog($id,self::title,"新建");
                    }
                    //添加日志
                    $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                    $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                    $this->logText(["type" => self::page, "text" => $text]);
                    //返回
                    $_SESSION['warn'] = $json['warn'];
                    $json['warn'] = 2;
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
                } else {
                    $this->rollback();
                }
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 关联采购申请
     * @return bool|string
     */
    public function addOrder(): bool|string
    {
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $formName         = 'saleOrderForm';
        $html =
            text(array("name" => "orderNo", "title" => "采购申请号")) .
            text(array("name" => "recordDate", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => "单据日期-单据日期")) .
            text(array("name" => "createTime", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => "需求日期-需求日期")) .
            text(array("name" => "code", "title" => "产品编码")) .
            text(array("name" => "materialName", "title" => "产品名称")) .
            text(array("name" => "model", "title" => "规格型号")) .
            hidden(array('name' => 'id', 'value' => $this->post('id'))) .
            hidden(array('name' => 'isTax', 'value' => $this->post('isTax'))) .
            hidden(array('name' => 'supplierId', 'value' => $this->post('supplierId'))) .
            hidden(array('name' => 'sourceId', 'value' => $this->post('sourceId') ? implode(',', $this->post('sourceId')) : ''));
        $button = "<input onclick=\"addRow('purchaseApply');$('#" . $layerId . "').remove()\" type='button' class='searchSub m-l-5' value='提交'>";
        $html = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     * 关联采购
     * @return bool|string
     */
    public function addOrderSearch(): bool|string
    {
        $sourceId = $this->post('sourceId') ? explode(',', $this->post('sourceId')) : [];
        $where = " pa.coid='" . self::$coid . "'  and mx.id not in ('" . implode("','", $sourceId) . "') and mx.num > mx.purchase_num ";
        $and = '';
        $like = [
            'pa.orderNo' => $this->post('orderNo'),
            'mat.code' => $this->post('code'),
            'mat.name' => $this->post('materialName'),
            'mat.model' => $this->post('model'),
        ];
        $equal = [
            'pa.state' => '已通过',
            'pa.isClose' => 0,
        ];
        if ($this->post('createTime')) {
            //需求日期
            $and .= self::timeComparison($this->post('createTime'), 'date', 'pa.demandDate');
        }
        if ($this->post('recordDate')) {
            //单据日期
            $and .= self::timeComparison($this->post('recordDate'), 'date', 'pa.recordDate');
        }
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $page = $this->page([
            "table" => " purchase_apply_detail as mx join purchase_apply as pa on mx.orderId = pa.id join material as mat on mx.materialId = mat.id ",
            "field" => "mx.id,mx.num,mx.purchase_num,pa.orderNo,pa.recordDate,pa.demandDate,mat.code,mat.name,mat.model",
            "where" => $where,
            'pageNum' => 50,
            "order" => "pa.recordDate desc,pa.`time` desc",
        ]);
        $tip = componentClass::promptSvg('采购申请可选范围：1、状态为已通过，2、待采购数量大于零');
        //获取表头
        $checkAll = $this->checkAll("saleOrderForm", "saleOrderDetailId");
        $tr[] = [$checkAll, '采购申请单号', '单据日期', '需求日期', '物料编号', '物料名称', '规格型号', '应采购数量', '已采购数量', '待采购数量'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "saleOrderDetailId", "value" => $array['id']),
            );
            $tr[] = array(
                $this->dominate($dominate),
                $array['orderNo'],
                $array['recordDate'],
                $array['demandDate'],
                $array['code'],
                $array['name'],
                $array['model'],
                self::lostZero($array['num'], 'numPrecision'),
                self::lostZero($array['purchase_num'], 'numPrecision'),
                self::lostZero($array['num'] - $array['purchase_num'], 'numPrecision'),
            );
        }
        $json['html'] = $page['hint'] .
            "<form name='saleOrderForm'>" .
                hidden(array('name' => 'isTax', 'value' => $this->post('isTax'))) .
                hidden(array('name' => 'id', 'value' => $this->post('id'))) .
                $this->tableMany(array("tr" => $tr, "showSort" => true, "sortTitle" => $tip, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 关联采购申请单
     */
    public function addOrderEdit()
    {
        $id = $this->post('id');//采购订单ID
        $isTax = $this->post('isTax');
        $mxIdArr = $this->post('saleOrderDetailId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择采购申请单';
        } else {
            $tr = [];
            foreach ($mxIdArr as $purchaseApplyDetailId) {
                $purchaseApplyMx = find(array('table' => "purchase_apply as a join purchase_apply_detail as b on a.id = b.orderId", 'single' => " b.id = '$purchaseApplyDetailId' order by list asc", 'field' => "b.*,a.orderNo"));
                $material = query('material', "id = '$purchaseApplyMx[materialId]'");
                $select = select(array(
                    'name' => 'rate[]',
                    'change' => 'countMoney',
                    'value' => $purchaseApplyMx['rate'] * 100,
                    'title' => '税率',
                    'option' => explode('，', para('taxRate'))
                ));
                $unitSelect = select(array(
                    'name' => 'unitDetail[]',
                    'data' => ['unit' => $purchaseApplyMx['unit']],
                    'change' => 'unitChange',
                    'option' => machiningOrderClass::unitOption($material['id']),
                    'title' => '单位',
                    'value' => $purchaseApplyMx['unit']
                ));
                //已进入采购订单的采购申请数量
                $orderNum = $this->purchaseNum($id, $purchaseApplyMx['id'], $purchaseApplyMx['unit']);
                $num = ($purchaseApplyMx['num'] - $orderNum) > 0 ? self::formattingFigure($purchaseApplyMx['num'] - $orderNum, 'numPrecision') : 0;
                $price = self::formattingFigure($purchaseApplyMx['price'], 'pricePrecision');

                $moneyRes = saleOrderClass::isTax($num, $price, $purchaseApplyMx['rate'], $isTax);
                $money = $moneyRes['money'];
                $taxMoney = $moneyRes['taxMoney'];
                $moneyWithTax = $moneyRes['moneyWithTax'];
                $suiji = self::getId();
                $tr[] = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $suiji)) .
                    hidden(array('name' => 'materialId[]', 'value' => $purchaseApplyMx['materialId'])) .
                    hidden(array('name' => 'sourceId[]', 'value' => $purchaseApplyMx['id'])),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $unitSelect,
                    text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision'), 'blur' => 'countMoney', 'value' => $num)),
                    text(array('name' => 'price[]', 'other' => self::digitalFiltering('pricePrecision'), 'blur' => 'countMoney', 'value' => $price)),
                    "<span class='rowMoney'>{$money}</span>",
                    $select,
                    "<span class='taxMoney'>{$taxMoney}</span>",
                    text(array('name' => 'moneyWithTax[]', 'other' => self::digitalFiltering(), 'blur' => 'calculatePrice', 'value' => $moneyWithTax)),
                    $purchaseApplyMx['orderNo'],
                    '采购申请单',
                    text(array('name' => 'mxText[]', 'class' => 'text textPrice', 'value' => '')),
                ];
            }
            $json['warn'] = 2;
            $json['html'] = $this->tableMany(array("tr" => $tr,"thead" => false));
        }
        return json_encode($json, 320);
    }

    /**
     * 关联供应商物料
     * @return bool|string
     */
    public function addSupplierPrice(): bool|string
    {
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $formName         = 'supplierPriceForm';
        $html =
            materialClass::typeSelect(name: 'type') .
            text(array("name" => "code", "title" => "物料编码")) .
            text(array("name" => "materialName", "title" => "物料名称")) .
            text(array("name" => "model", "title" => "规格型号")) .
            hidden(array('name' => 'id', 'value' => $this->post('id'))) .
            hidden(array('name' => 'isTax', 'value' => $this->post('isTax'))) .
            hidden(array('name' => 'supplierId', 'value' => $this->post('supplierId'))) .
            hidden(array('name' => 'sourceId', 'value' => $this->post('sourceId') ? implode(',', $this->post('sourceId')) : ''));
        $button = "<input onclick=\"addRow('supplierPrice');removeSelectedContent('" . $formName . "')\" type='button' class='searchSub m-l-5' value='继续添加'>";
        $button .= "<input onclick=\"addRow('supplierPrice');$('#" . $layerId . "').remove()\" type='button' class='searchSub m-l-5' value='提交'>";
        $html = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     * 关联供应商物料
     * @return bool|string
     */
    public function addSupplierPriceSearch(): bool|string
    {
        $sourceId = $this->post('sourceId') ? explode(',', $this->post('sourceId')) : [];
        $where = " ssp.coid='" . self::$coid . "'  and ssp.id not in ('" . implode("','", $sourceId) . "')";
        $like = [
            'mat.code' => $this->post('code'),
            'mat.name' => $this->post('materialName'),
            'mat.model' => $this->post('model'),
            'mat.typePath' => $this->post('type'),
        ];
        $equal = [
            'ssp.supplierId' => $this->post('supplierId'),
        ];
        $where .= search(["like" => $like, "=" => $equal]);
        $page = $this->page([
            "table" => " store_supplier_price as ssp join material as mat on ssp.materialId = mat.id ",
            "field" => "ssp.id,mat.typeId,mat.code,mat.name,mat.model,mat.typeName",
            "where" => $where,
            'pageNum' => 50,
            "order" => "ssp.`time` desc",
        ]);
        $materialObj = new materialClass();
        //获取表头
        $checkAll = $this->checkAll("supplierPriceForm", "supplierPriceId");
        $tr[] = [$checkAll, '分类', '物料编码', '物料名称', '规格型号'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "supplierPriceId", "value" => $array['id']),
            );
            $tr[] = array(
                $this->dominate($dominate),
                $array['typeName'],
                $array['code'],
                $array['name'],
                $array['model'],
            );
        }
        $json['html'] = $page['hint'] .
            "<form name='supplierPriceForm'>" .
                hidden(array('name' => 'isTax', 'value' => $this->post('isTax'))) .
                hidden(array('name' => 'id', 'value' => $this->post('id'))) .
                $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 关联供应商价格表
     */
    public function addSupplierPriceEdit()
    {
        $id = $this->post('id');//采购订单ID
        $isTax = $this->post('isTax');
        $mxIdArr = $this->post('supplierPriceId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择供应商物料';
        } else {
            $tr = [];
            foreach ($mxIdArr as $supplierPriceId) {
                $store_supplier_price = query('store_supplier_price', "id = '$supplierPriceId'");
                $material = query('material', "id = '$store_supplier_price[materialId]'");
                $select = select(array(
                    'name' => 'rate[]',
                    'change' => 'countMoney',
                    'value' => '',
                    'title' => '税率',
                    'option' => explode('，', para('taxRate'))
                ));
                $unitSelect = select(array(
                    'name' => 'unitDetail[]',
                    'data' => ['unit' => $store_supplier_price['unit']],
                    'change' => 'unitChange',
                    'option' => machiningOrderClass::unitOption($material['id']),
                    'title' => '单位',
                    'value' => $store_supplier_price['unit']
                ));
                $num = 0;
                $price = self::formattingFigure($store_supplier_price['price'], 'pricePrecision');
                $moneyRes = saleOrderClass::isTax($num, $price, 0, $isTax);
                $money = $moneyRes['money'];
                $taxMoney = $moneyRes['taxMoney'];
                $moneyWithTax = $moneyRes['moneyWithTax'];
                $suiji = self::getId();
                $tr[] = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $suiji)) .
                    hidden(array('name' => 'materialId[]', 'value' => $store_supplier_price['materialId'])) .
                    hidden(array('name' => 'sourceId[]', 'value' => $store_supplier_price['id'])),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $unitSelect,
                    text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision'), 'blur' => 'countMoney', 'value' => $num)),
                    text(array('name' => 'price[]', 'other' => self::digitalFiltering('pricePrecision'), 'blur' => 'countMoney', 'value' => $price)),
                    "<span class='rowMoney'>{$money}</span>",
                    $select,
                    "<span class='taxMoney'>{$taxMoney}</span>",
                    text(array('name' => 'moneyWithTax[]', 'other' => self::digitalFiltering(), 'blur' => 'calculatePrice', 'value' => $moneyWithTax)),
                    '',
                    '供应商价格本',
                    text(array('name' => 'mxText[]', 'class' => 'text textPrice', 'value' => '')),
                ];
            }
            $json['warn'] = 2;
            $json['html'] = $this->tableMany(array("tr" => $tr,"thead" => false));
        }
        return json_encode($json, 320);
    }


    /**
     *
     * @return bool|string
     */
    public function addMx()
    {
        $materialClassObj = new materialClass();
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $formName         = 'mxForm';
        $notAllowRepeat   = 1;
        $attach = '';
        if ($this->post('contractId')) {
            $attach .= " and id in (select materialId from purchase_contract_detail where coid = '" . self::$coid . "' and orderId = '" . $this->post('contractId') . "')";
        }
        $data             = [
            'sub'            => " onclick=\"addRow();$('#" . $layerId . "').remove()\" ",
            'continueAdding' => $notAllowRepeat ? " onclick=\"addRow();removeSelectedContent('" . $formName . "')\" " : " onclick=\"addRow();\" ",
            'hidden'         => hidden(["name" => "notAllowRepeat", "value" => $notAllowRepeat]) .
                hidden(["name" => "supplyControl", "value" => '允许采购']) .
                hidden(["name" => "attach", "value" => $attach]) .
                hidden(array('name' => 'isTax', 'value' => $this->post('isTax'))) .
                hidden(array('name' => 'contractId', 'value' => $this->post('contractId'))) .
                hidden(array('name' => 'id', 'value' => $this->post('id'))) .
                hidden(array('name' => 'materialId', 'value' => $this->post('materialId') ? implode(',', $this->post('materialId')) : '')),
        ];
        return $materialClassObj->addMx($data);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $id = $this->post('id');
        $mxIdArr = $this->post('mxId');
        $contractId = $this->post('contractId');
        $isTax = $this->post('isTax');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择物料';
        } else {
            $tr = [];
            foreach ($mxIdArr as $mxId) {
                $material = query('material', "id = '$mxId'");
                $unit = $material['unit'];
                if ($contractId) {
                    $purchaseContractMx = query('purchase_contract_detail', "materialId = '$mxId' and orderId = '$contractId'");
                    //已进入采购单的合同明细数量
                    $orderNum = $this->purchaseNum($id, $purchaseContractMx['id'], $purchaseContractMx['unit']);
                    $unit = $purchaseContractMx['unit'];
                }
                $orderNum = $orderNum ?? 0;
                $purchaseContractMx['num'] = $purchaseContractMx['num'] ?? 0;
                $price = $purchaseContractMx['price'] ?? $material['buyPrice'];
                $price = self::formattingFigure($price, 'pricePrecision');
                $num = ($purchaseContractMx['num'] - $orderNum) > 0 ? self::formattingFigure($purchaseContractMx['num'] - $orderNum, 'numPrecision') : 0;
                $rate = $purchaseContractMx['rate'] ?? $material['buyRate'];
                $sourceId = $purchaseContractMx['id'] ?? '';

                $moneyRes = saleOrderClass::isTax($num, $price, $rate, $isTax);
                $money = $moneyRes['money'];
                $taxMoney = $moneyRes['taxMoney'];
                $moneyWithTax = $moneyRes['moneyWithTax'];
                $unitSelect = select(array(
                    'name' => 'unitDetail[]',
                    'data' => ['unit' => $unit],
                    'change' => 'unitChange',
                    'option' => machiningOrderClass::unitOption($material['id']),
                    'title' => '单位',
                    'value' => $unit
                ));
                $select = select(array(
                    'name' => 'rate[]',
                    'change' => 'countMoney',
                    'value' => $rate * 100,
                    'title' => '税率',
                    'option' => explode('，', para('taxRate'))
                ));
                $suiji = self::getId();
                $tr[] = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $suiji)) .
                    hidden(array('name' => 'materialId[]', 'value' => $mxId)) .
                    hidden(array('name' => 'sourceId[]', 'value' => $sourceId)),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $unitSelect,
                    text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision'), 'blur' => 'countMoney', 'value' => $num)),
                    text(array('name' => 'price[]', 'other' => self::digitalFiltering('pricePrecision'), 'blur' => 'countMoney', 'value' => $price)),
                    "<span class='rowMoney'>{$money}</span>",
                    $select,
                    "<span class='taxMoney'>{$taxMoney}</span>",
                    text(array('name' => 'moneyWithTax[]', 'other' => self::digitalFiltering(), 'blur' => 'calculatePrice', 'value' => $moneyWithTax)),
                    '',
                    '',
                    text(array('name' => 'mxText[]', 'class' => 'text textPrice', 'value' => '')),
                ];
            }
            $json['warn'] = 2;
            $json['html'] = $this->tableMany(array("tr" => $tr,"thead" => false));
        }
        return json_encode($json, 320);
    }

    /**
     * 启用/停用
     */
    public function stateSwitch(): bool|string
    {
        $isClose = $this->post('type');
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否确认" . ($isClose == 1 ? '关闭业务' : '开启业务') . "此订单？",
            ),
        ), 'hidden' => hidden(array('name' => 'type', 'value' => $isClose))));
        //返回
        return $this->layer(array("title" => "订单状态", "height" => 165, "html" => $html, 'formTwo' => 'listForm'));
    }

    /**
     * 启用/停用
     */
    public function stateSwitchEdit(): bool|string
    {
        $idArr = $this->post('id') ? [$this->post('id')] : $this->post('listId');
        $isClose = $this->post('type');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有" . self::title . "的编辑权限";
        } elseif (empty($idArr) || !is_array($idArr)) {
            $json['warn'] = "请选择数据";
        } else {
            $field = [
                'isClose' => $isClose,
            ];
            $json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id in ('" . implode("','", $idArr) . "')"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $type = $isClose == 1 ? '关闭' : '开启';
                foreach ($idArr as $id) {
                    self::insertOperateLog($id,self::title,$type);
                }
                //添加日志
                $text = $this->control['name'] . $type . "了" . self::title . "， id：【" . implode(",", $idArr) . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $type . '成功';
                $json['warn'] = 2;
            }
        }
        //返回
        return json_encode($json, 320);
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );

            $button = [];
            if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                $button[] = [
                    "name" => "复核",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($info['state'] == '草稿') {
                if ($this->power(self::page, "edit")) {
                    //按钮
                    $button[] = [
                        "name" => "提交",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'commit', "id" => $info['id']],
                        'style' => 'li-btn-blue-bg',
                    ];
                    //按钮
                    $button[] = [
                        "name" => "编辑",
                        "type" => "顶部页卡",
                        "title" => self::title,
                        "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                    ];
                }
                if ($this->power(self::page, "del")) {
                    //按钮
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }

            }
            //按钮
            $button[] = [
                "name" => "打印",
                "type" => "点击事件",
                "fun" => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$info['id']}')",
            ];


            if ($this->power(self::page, "confirm") && $info['state'] != '草稿' && !$info['isClose']) {
                $button[] = [
                    "name" => "撤回",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'cancel', "id" => $info['id']],
                ];
            }
            if ($this->power(self::page, "edit") && $info['state'] == '已确认') {
                //按钮
                $isClose = $info['isClose'] == 1 ? 0 : 1;
                $name = $info['isClose'] == 1 ? '业务开启' : '业务关闭';
                $button[] = [
                    "name" => $name,
                    "type" => "点击事件",
                    "fun" => "layer('" . self::page . "','stateSwitch',{id:'" . $info['id'] . "',type:'{$isClose}'})",
                ];
            }
            $button[] = [
                "name" => "单据追踪",
                "type" => "顶部页卡",
                "title" => self::title,
                "url" => $this->root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=采购订单&id=" . $info['id'],
            ];
            //操作记录
            $button[] = self::operateLogBut($info['id'],1);

            $isTax = $info['isTax'] ? '含税' : '不含税';
            $tr[] = ['物料编码', '物料名称', '规格型号', '单位', '数量', $isTax . '单价(' . static::$unit . ')', '未税金额（' . static::$unit . '）', '税率%', '税额（' . static::$unit . '）', '价税合计（' . static::$unit . '）', '关联源单', '源单类型', '备注'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($result['array'] as $array) {
                $relativeNo = '';
                $relativeType = '';
                $material = query('material', " id = '$array[materialId]'");
                if ($array['sourceTable'] == 'purchase_apply_detail') {
                    $targetInfo = query('purchase_apply_detail', "id = '$array[sourceId]'");
                    $purchaseApply = query('purchase_apply', "id = '$targetInfo[orderId]'");
                    $relativeNo = $purchaseApply['orderNo'];
                    $relativeType = '采购申请单';
                } elseif ($array['sourceTable'] == 'purchase_demands') {
                    $targetInfo = query('purchase_demands', "id = '$array[sourceId]'");
                    if ($targetInfo['sourceType'] == '销售订单') {
                        $saleOrder = query('sale_order', "id = '$targetInfo[sourceId]'");
                        $relativeNo = $saleOrder['orderNo'];
                        $relativeType = '销售订单';
                    } elseif ($targetInfo['sourceType'] == '生产计划') {
                        $saleOrder = query('machining_order', "id = '$targetInfo[sourceId]'");
                        $relativeNo = $saleOrder['orderNo'];
                        $relativeType = '生产计划单';
                    }
                } elseif ($array['sourceTable'] == 'purchase_contract_detail') {
                    $targetInfo = query('purchase_contract_detail', "id = '$array[sourceId]'");
                    $purchaseContract = query('purchase_contract', "id = '$targetInfo[orderId]'");
                    $relativeNo = $purchaseContract['orderNo'];
                    $relativeType = '采购合同';
                }
                $tr[] = [
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    self::lostZero($array['num'], 'numPrecision'),
                    self::lostZero($array['price'], 'pricePrecision'),
                    self::formattingFigure($array['money'] - $array['taxMoney']),
                    ($array['rate'] * 100) . '%',
                    self::lostZero($array['taxMoney']),
                    self::lostZero($array['money']),
                    $relativeNo,
                    $relativeType,
                    $array['text'],
                ];
            }
            $total = find(array(
                'table' => self::tableMx,
                'field' => "
                ifnull(sum(num),0) as num,
                ifnull(sum(money),0) as totalMoney,
                ifnull(sum(money-taxMoney),0) as money,
                ifnull(sum(taxMoney),0) as taxMoney",
                'single' => "orderId = '$info[id]' "
            ));
            $total['num'] = $total['num'] ? self::lostZero($total['num'], 'numPrecision') : 0;
            $total['totalMoney'] = $total['totalMoney'] ? self::lostZero($total['totalMoney']) : 0;
            $total['taxMoney'] = $total['taxMoney'] ? self::lostZero($total['taxMoney']) : 0;
            $total['money'] = $total['money'] ? self::lostZero($total['money']) : 0;
            $total_tr = [
                    4=>$total['num'],
                    6=>$total['money'],
                    8=>$total['taxMoney'],
                    9=>$total['totalMoney'],
            ];
            $supplier = query('supplier', "id = '$info[supplierId]'");
            $contract = query('purchase_contract', "id = '$info[contractId]'");
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '详细信息' => array(
                    array(
                        "供应商" => $supplier['name'],
                        "合同名称" => $contract['name'],
                        "收货人" => $info['contactName'],
                        "收货电话" => $info['contactTel'],
                    ),
                    array(
                        "结算方式" => $info['settlementType'] . ($info['settlementType'] == '月结' ? '-' . $info['settlementDay'] . '天' : ''),
                        "单据日期" => self::null($info['recordDate']),
                        "交货日期" => self::null($info['deliveryDate']),
                        "实际交货日期" => self::null($info['actual_delivery_date']),
                    ),
                    array(
                        "收货地址" => pre($info['address']),
                    ),
                    array(

                        "备注" => pre($info['text']),
                    ),
                    array(
                        "单据编号" => $info['orderNo'],
                        "制单人" => self::findStaff($info['stid']),
                        "状态" => $info['state']
                    ),
                    array(
                        '单据标签' => orderTagClass::getTagName($info['id'])
                    )
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '采购明细',
                'html' => $this->listTable(array('tr' => $tr, 'showEmpty' => true, 'total' => $total_tr, 'showSort' => true)),
            ]);
            $data['html'] .= $this->detailBlock([
                '附件' => fileUploadClass::showFile($info['id'], '采购单')
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }
    /**
     * 确认
     */
    public function batchSureEdit()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有操作的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id'");
                $field = [
                    'state' => '已确认',
                    'checkId' => self::$stid,
                    'confirmTime' => $this->time
                ];
                if (empty($info['id'])) {
                    $json['warn'] = '未找到此采购单';
                    goto resp;
                } elseif (!in_array($info['state'],['草稿','待确认'])) {
                    $json['warn'] = '此采购单不是草稿、待确认状态，不能确认';
                    goto resp;
                }
                $this->startTrans();
                $json['warn'] = update(array(
                    "table" => self::table,
                    "field" => $field,
                    "where" => "id = '$info[id]'",
                ));
                resp:
                if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                    // 根据采购数量关闭采购申请
                    $this->updatePurchaseApply($info);
                    $this->commitTrans();
                    if($info['state'] == '草稿') {
                        $operate = "提交，确认";
                    }else{
                        $operate = "确认";
                    }
                    auditClass::operateRecord($id, self::title, $operate);
                    //添加日志
                    $warn = $operate."成功";
                    $x++;
                } else {
                    $this->rollback();
                    $warn = $json['warn'];
                }

                $text .= self::title . "单据编号【" . $info['orderNo'] . "】，ID【" . $id . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "提交，确认了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "提交，确认了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已确认',
            'checkId' => self::$stid,
            'confirmTime' => $this->time
        ];
        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此采购单';
        } elseif ($info['state'] != '待确认') {
            $json['warn'] = '此采购单不是待确认状态，不能确认';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                // 单据是否需要复核
                if(!in_array(self::page,self::$publicSettings['documentReview'])) {
                    self::insertOperateLog($info['id'],self::title,"提交、复核");
                }else{
                    self::insertOperateLog($info['id'],self::title,"复核");
                }
                // 根据采购数量关闭采购申请
                $this->updatePurchaseApply($info);
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 更新采购申请
     */
    private function updatePurchaseApply($info): bool|string
    {
        $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"));
        $apply_order_id = [];
        foreach ($result['array'] as $array) {
            if (!empty($array['sourceId'])) {
                $purchase_apply_detail = query('purchase_apply_detail', "id = '$array[sourceId]'", "id,orderId,num,purchase_num");
                // 增加采购申请的已采购数量
                $purchaseTotal         = find(array(
                    'table'  => self::tableMx,
                    'single' => " sourceId = '$purchase_apply_detail[id]' and orderId in (select id from purchase_order where coid = '" . self::$coid . "' and state = '已确认') ",
                    'field'  => "ifnull(sum(num),0) as num,ifnull(sum(receive_num),0) as receive_num"
                ));
                update(array(
                    "table" => 'purchase_apply_detail',
                    "field" => ['purchase_num' => $purchaseTotal['num'],'receive_num' => $purchaseTotal['receive_num']],
                    "where" => "id = '$purchase_apply_detail[id]'",
                ));
                if (!in_array($purchase_apply_detail['orderId'], $apply_order_id)) $apply_order_id[] = $purchase_apply_detail['orderId'];
            }
        }
        //修改主订单
        foreach ((array)$apply_order_id as $orderId) {
            // 自动关闭采购申请
            $applyClose = optionSettingClass::getSettingItem('采购', 'applyClose');
            if($applyClose) {
                if (static::total(array('table' => 'purchase_apply_detail', 'where' => " orderId = '".$orderId."' and coid = '".self::$coid."' and purchase_num < num ")) == 0){
                    update(array(
                        "table" => 'purchase_apply',
                        "field" => ['isClose'=>1],
                        "where" => "id = '$orderId'",
                    ));
                }
            }
        }
        return true;
    }

    /**
     * 撤回
     */
    public function cancelEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '草稿',
            'checkId' => '',
            'confirmTime' => ''
        ];
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有撤回权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此采购单';
        } elseif ($info['state'] == '草稿') {
            $json['warn'] = '此采购单草稿状态，无需撤回';
        } elseif (static::total(array('table' => 'purchase_get_order_detail', "where" => "sourceId in (select id from " . self::tableMx . " where orderId = '$info[id]') and coid = '" . self::$coid . "'")) > 0) {
            $json['warn'] = '此采购单已存在有收货的单据，不能撤回';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                // 根据采购数量关闭采购申请
                $this->updatePurchaseApply($info);
                self::insertOperateLog($info['id'],self::title,"撤回");
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * Desc : 提交前数据验证
     * User : you name
     * Date : 2023-11-17 16:04
     * @param $info
     * @return string|bool
     */
    public function dataValidation($info): string|bool
    {
        $annotation = [
            'type' => '业务类型',
            'supplierId' => '供应商',
            'recordDate' => '单据日期',
            'deliveryDate' => '交货日期',
        ];
        $rules = [
            'type' => 'required',
            'supplierId' => 'required',
            'recordDate' => 'required|date',
            'deliveryDate' => 'required|date',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($info, $rules)->isOk();
        if ($result === false) {
            return $vt->getErrs()[0];  // 多个规则提示最前面一条
        }
        $result = find(array('table' => self::tableMx, 'field' => 'id,materialId,num,unit,price', 'where' => "orderId = '$info[id]' order by list"));
        if(count($result['array']) == 0){
            return "请完善采购明细";
        }
        if(static::is_null_array(array_column($result['array'],'materialId'))){
            return "采购明细中物料不能为空";
        }
        if(static::is_null_array(array_column($result['array'],'unit'))){
            return "采购明细中【单位】不能为空";
        }
        if(static::is_null_array(array_column($result['array'],'price'))){
            return "采购明细中【单价】不能为空";
        }
        if(static::is_null_array(array_column($result['array'],'num'),false)){
            return "采购明细中【数量】不能为空，且必须大于0";
        }

        return true;
    }
    /**
     * 提交
     */
    public function commitEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待确认',
        ];
        //提交前数据验证
        $json['warn'] = $this->dataValidation($info);
        if($json['warn'] !== true){
            goto resp;
        }
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此采购单';
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = '此采购单不是草稿状态，不能提交';
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                // 单据是否需要复核
                if(!in_array(self::page,self::$publicSettings['documentReview'])){
                    $resultJson = $this->confirmEdit();
                    $json = json_decode($resultJson,true);
                    if ($json['warn'] != 2){
                        $this->rollback();
                        goto resp;
                    }
                }else {
                    self::insertOperateLog($info['id'],self::title,"提交");
                }
                $this->commitTrans();
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = $word = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认此采购单，确认后将不可修改？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认提交此采购单？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认撤回此采购单？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'close':
                $act = 'close';
                $msg = '业务关闭';
                $title = '是否确认批量关闭采购订单？';
                $function = 'closeEdit';
                $form = self::page . 'OperateForm, listForm, quoForm';
                $power = '';
                $word = true;
                break;
            case 'batchSure':
                $act = 'edit';
                $msg = '提交确认';
                $title = '是否确认批量提交确认采购订单？';
                $function = 'batchSureEdit';
                $form = self::page . 'OperateForm, listForm, quoForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm, quoForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 批量关闭采购订单
     *
     * @return bool|string
     */
    public function closeEdit()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有操作的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ", "isClose");
                if ($info['isClose'] == 1) {
                    $warn = "操作失败：已关闭，请勿重复操作";
                } else {
                    update(array('table' => self::table, 'field' => ['isClose' => 1], 'where' => " id = '$id' "));
                    self::insertOperateLog($id,self::title,"关闭");
                    //返回
                    $warn = "关闭成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $id . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "关闭了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "关闭了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = "删除失败：已确认，暂不能删除";
                } else {
                    //最后删除基本参数
                    fileClass::deleteFile($id);
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 批量打印
     *
     * @return string
     */
    public function batchPrint(): string
    {
        $lists = $this->get('lists');
        if (empty($lists)) {
            exit('参数错误');
        } else {
            $listId = base64_decode($lists, true);
            $array = explode(',', $listId);
            $data = [];
            foreach ($array as $id) {
                $data[] = static::printPage($id, false);
            }
            return (new printTemplateClass())->start(self::page, $data);
        }
    }

    /**
     * 打印
     *
     * @return string
     */
    public function printPage($param = '', $isReturn = true): string|array
    {
        $id = $param ?: $this->get('id');
        $info = query(self::table, " id = '$id'");
        $info['companyName'] = query('company', "coid = '" . self::$coid . "'")['name']; //公司名称//公司名称
        $info['title'] = self::title;
        $info['printTime'] = $this->time;
        $info['stid'] = self::findStaff($info['stid']);
        $info['checkId'] = '';
        $info['supplierName'] = query('supplier', "id = '$info[supplierId]'")['name'];
        $info['qr'] = "source=" . self::table . "&id=" . $info['id'];
        $info['tags'] = orderTagClass::getTagName($info['id']);
        $detail = find(['table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"])['array'];
        $items = [];
        $x = 1;
        $totalNum = 0;
        $totalMoney = 0;
        foreach ($detail as $array) {
            $material = query('material', "id = '$array[materialId]'");
            $items[] = [
                'no' => $x,
                'materialCode' => $material['code'],
                'materialName' => $material['name'],
                'price' => self::lostZero($array['price'], 'pricePrecision'),
                'rate' => ($array['rate'] * 100) . '%',
                'taxMoney' => self::lostZero($array['taxMoney']),
                'moneyWithOutTax' => self::formattingFigure($array['money'] - $array['taxMoney']),
                'money' => self::lostZero($array['money']),
                'model' => $material['model'],
                'unit' => $array['unit'],
                'num' => self::lostZero($array['num'], 'numPrecision'),
                'text' => $array['text'],
            ];
            $x++;
            $totalNum += $array['num'];
            $totalMoney += $array['money'];
        }
        $append = [
            'no' => '合计',
            'num' => $totalNum,
            'money' => $totalMoney
        ];
        $items[] = $append;
        $info['detail'] = $items;
        if ($isReturn) {
            return (new printTemplateClass())->start(self::page, $info);
        } else {
            return $info;
        }
    }


    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'单据日期',
                    'aliasName'=>'单据日期',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'供应商编码',
                    'aliasName'=>'供应商编码',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'供应商名称',
                    'aliasName'=>'供应商名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'采购合同编号',
                    'aliasName'=>'采购合同编号',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'采购合同名称',
                    'aliasName'=>'采购合同名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'结算方式',
                    'aliasName'=>'结算方式',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'结算周期',
                    'aliasName'=>'结算周期',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'交货日期',
                    'aliasName'=>'交货日期',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'收货人',
                    'aliasName'=>'收货人',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'收货电话',
                    'aliasName'=>'收货电话',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'收货地址',
                    'aliasName'=>'收货地址',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'单据备注',
                    'aliasName'=>'单据备注',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'是否含税',
                    'aliasName'=>'是否含税(是/否，默认否)',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'数量',
                    'aliasName'=>'数量',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'单价',
                    'aliasName'=>'单价',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'税率',
                    'aliasName'=>'税率%',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'价税合计',
                    'aliasName'=>'价税合计',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',

                    'isMust'=>false,
                ],
            ]
        };
    }


    /**
     * 关联合同物料明细
     * @return bool|string
     */
    public function addContractMx(): bool|string
    {
        if (static::isNull($this->post['supplierId'])) {
            return json_encode(['warn' => '请选择供应商', 320]);
        } elseif (static::isNull($this->post['contractId'])) {
            return json_encode(['warn' => '请选择采购采购合同', 320]);
        }  else {
            $html   =
                text(array("name" => "orderNo", "title" => "采购合同单号")) .
                text(array("name" => "signedDate", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => "签订日期-签订日期")) .
                self::moreContainer(materialClass::typeSelect(name: 'type') .
                    text(array("name" => "code", "title" => "产品编码")) .
                    text(array("name" => "materialName", "title" => "产品名称")) .
                    text(array("name" => "model", "title" => "规格型号")) .
                    text(array("name" => "attrName", "title" => "属性"))) .
                hidden(array('name' => 'id', 'value' => $this->post('id'))) .
                hidden(array('name' => 'isTax', 'value' => $this->post('isTax'))) .
                hidden(array('name' => 'supplierId', 'value' => $this->post('supplierId'))) .
                hidden(array('name' => 'purchasing_unit', 'value' => $this->post('purchasing_unit'))) .
                hidden(array('name' => 'contractId', 'value' => $this->post('contractId'))) .
                hidden(array('name' => 'nature', 'value' => $this->post('type'))) .
                hidden(array('name' => 'sourceId', 'value' => $this->post('sourceId') ? implode(',', $this->post('sourceId')) : ''));
            $button = "<input style='margin-left: 5px' onclick=\"addRow('addContractMx')\" type='button' class='searchSub' value='提交'>";
            $html   = "<div style='padding: 10px'>" . $this->search($html, null, $button) . "</div>";
            return $this->layer(array("title" => "添加", "height" => 600, "width" => 1000, "html" => $html,'button'=>false));
        }
    }

    /**
     * 关联合同物料明细
     * @return bool|string
     */
    public function addContractMxSearch(): bool|string
    {
        $sourceId = $this->post('sourceId') ? explode(',', $this->post('sourceId')) : [];
        $where    = " mx.id not in ('" . implode("','", $sourceId) . "') and mx.id not in (select sourceId from purchase_order_detail where coid = '" . self::$coid . "')  ";
        $and      = '';
        if ($this->post('type')) {
            $allTypeId = materialClass::getAllChildTypeId($this->post('type'));
            $and       .= " and mat.typeId in ('" . implode("','", $allTypeId) . "')";
        }
        $like  = [
            'pa.orderNo'         => $this->post('orderNo'),
            'mx.resource_number' => $this->post('resource_number'),
            'mat.code'           => $this->post('code'),
            'mat.name'           => $this->post('materialName'),
            'mat.model'          => $this->post('model'),
            'sku.name'           => $this->post('attrName'),
        ];
        $equal = [
            'pa.coid'            => self::$coid,
            'pa.id'              => $this->post('contractId'),
            'pa.purchasing_unit' => $this->post('purchasing_unit'),
            'pa.nature'          => $this->post('nature'),
            'pa.state'           => '已通过',
        ];
        if ($this->post('signedDate')) {
            //需求日期
            $and .= self::timeComparison($this->post('signedDate'), 'date', 'pa.signedDate');
        }

        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $page  = $this->page([
            "table"   => " purchase_contract_detail as mx join purchase_contract as pa on mx.orderId = pa.id join material as mat on mx.materialId = mat.id  ",
            "field"   => "mx.id,pa.orderNo,pa.signedDate,mat.code,mat.name,mat.model,mat.typeId,mat.unit,mat.height,mat.length,mat.width,mx.num",
            "where"   => $where,
            'pageNum' => 50,
            "order"   => "pa.signedDate desc,pa.`time` desc",
        ]);
        //获取表头
        $checkAll = $this->checkAll("purchaseContractForm", "saleOrderDetailId");
        $tr[]     = [$checkAll, '采购合同单号', '物料编号', '物料名称', '规格型号', '单位', '采购量(吨)', '签订日期'];

        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "saleOrderDetailId", "value" => $array['id']),
            );
            $tr[]     = array(
                $this->dominate($dominate),
                $array['orderNo'],
                $array['code'],
                $array['name'],
                $array['model'],
                $array['unit'],
                self::lostZero($array['num'], 'numPrecision'),
                $array['signedDate'],
            );
        }
        $json['html'] = $page['hint'] . "<form name='purchaseContractForm'>" . hidden(array('name' => 'isTax', 'value' => $this->post('isTax'))) . hidden(array('name' => 'id', 'value' => $this->post('id'))) . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 关联合同物料明细
     */
    public function addContractMxEdit()
    {
        $id = $this->post('id');//采购订单ID
        $isTax = $this->post('isTax');
        $mxIdArr = $this->post('saleOrderDetailId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择采购申请单';
        } else {
            $tr = [];
            foreach ($mxIdArr as $purchaseApplyDetailId) {
                $purchaseApplyMx = find(array('table' => "purchase_contract as a join purchase_contract_detail as b on a.id = b.orderId", 'single' => " b.id = '$purchaseApplyDetailId' order by list asc", 'field' => "b.*,a.orderNo"));
                $material = query('material', "id = '$purchaseApplyMx[materialId]'");
                $select = select(array(
                    'name' => 'rate[]',
                    'change' => 'countMoney',
                    'value' => $purchaseApplyMx['rate'] * 100,
                    'title' => '税率',
                    'option' => explode('，', para('taxRate'))
                ));
                $unitSelect = select(array(
                    'name' => 'unitDetail[]',
                    'data' => ['unit' => $purchaseApplyMx['unit']],
                    'change' => 'unitChange',
                    'option' => machiningOrderClass::unitOption($material['id']),
                    'title' => '单位',
                    'value' => $purchaseApplyMx['unit']
                ));
                //已进入采购订单的采购申请数量
                $orderNum = $this->purchaseNum($id, $purchaseApplyMx['id'], $purchaseApplyMx['unit']);
                $num = ($purchaseApplyMx['num'] - $orderNum) > 0 ? self::formattingFigure($purchaseApplyMx['num'] - $orderNum, 'numPrecision') : 0;
                $price = self::formattingFigure($purchaseApplyMx['price'], 'pricePrecision');

                $moneyRes = saleOrderClass::isTax($num, $price, $purchaseApplyMx['rate'], $isTax);
                $money = $moneyRes['money'];
                $taxMoney = $moneyRes['taxMoney'];
                $moneyWithTax = $moneyRes['moneyWithTax'];
                $suiji = self::getId();
                $tr[] = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $suiji)) .
                    hidden(array('name' => 'materialId[]', 'value' => $purchaseApplyMx['materialId'])) .
                    hidden(array('name' => 'sourceId[]', 'value' => $purchaseApplyMx['id'])),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $unitSelect,
                    text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision'), 'blur' => 'countMoney', 'value' => $num)),
                    text(array('name' => 'price[]', 'other' => self::digitalFiltering('pricePrecision'), 'blur' => 'countMoney', 'value' => $price)),
                    "<span class='rowMoney'>{$money}</span>",
                    $select,
                    "<span class='taxMoney'>{$taxMoney}</span>",
                    text(array('name' => 'moneyWithTax[]', 'other' => self::digitalFiltering(), 'blur' => 'calculatePrice', 'value' => $moneyWithTax)),
                    $purchaseApplyMx['orderNo'],
                    '采购合同单',
                    text(array('name' => 'mxText[]', 'class' => 'text textPrice', 'value' => '')),
                ];
            }
            $json['warn'] = 2;
            $json['html'] = $this->tableMany(array("tr" => $tr,"thead" => false));
        }
        return json_encode($json, 320);
    }
}
